package top.z.work.module.system.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import top.z.work.framework.common.exception.ExceptionUtil;
import top.z.work.module.system.constant.SystemDeptErrorCode;
import top.z.work.module.system.entity.SystemDept;
import top.z.work.module.system.entity.SystemUser;
import top.z.work.module.system.mapper.SystemDeptMapper;
import top.z.work.module.system.service.SystemDeptService;
import top.z.work.module.system.service.SystemUserService;

/**
 * 部门表ServiceImpl
 *
 * @author zaoangod
 * @since 2024-03-22
 */
@Service
public class SystemDeptServiceImpl extends ServiceImpl<SystemDeptMapper, SystemDept> implements SystemDeptService {

    @Resource
    SystemUserService systemUserService;

    @Override
    public Boolean removeDept(Long identity) {
        if (identity == null) {
            throw ExceptionUtil.exception(SystemDeptErrorCode.DEPT_IDENTITY_IS_NULL);
        }
        long deptCount = this.count(QueryChain.of(SystemDept.class).eq(SystemDept::getParent, identity));
        if (deptCount != 0) {
            throw ExceptionUtil.exception(SystemDeptErrorCode.DEPT_HAS_CHILDREN);
        }
        long userCount = systemUserService.count(QueryChain.of(SystemUser.class).eq(SystemUser::getDeptId, identity));
        if (userCount != 0) {
            throw ExceptionUtil.exception(SystemDeptErrorCode.DEPT_ASSIGN_TO_USER);
        }
        return this.removeById(identity);
    }

}
